<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 显示提示信息 -->
      <el-alert
        title="警告提示的文案"
        type="warning"
        center
        show-icon
        :closable="false"
      ></el-alert>

      <!-- 显示进度的步骤 -->
      <el-steps
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 显示选项卡内容 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-tabs
          v-model="activeIndex"
          :tab-position="'left'"
          :before-leave="tabBeforeLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane
            label="基本信息"
            name="0"
          >
            <!-- 展示表单内部的文本框 -->
            <el-form-item
              label="商品名称"
              prop="goods_name"
            >
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item
              label="商品价格"
              prop="goods_price"
            >
              <el-input
                v-model="addForm.goods_price"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="商品重量"
              prop="goods_weight"
            >
              <el-input
                v-model="addForm.goods_weight"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="商品数量"
              prop="goods_number"
            >
              <el-input
                v-model="addForm.goods_number"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="分类选项"
              prop="goods_cat"
            >
              <!-- 显示级联选择器 -->
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cascaderProps"
                clearable
                @change="changeCate"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane
            label="商品参数"
            name="1"
          >
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyDataList"
              :key="item.attr_id"
            >
              <!-- 显示对应的单选框 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="cd"
                  v-for="(cd, i) in item.attr_vals"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane
            label="商品属性"
            name="2"
          >
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyDataList"
              :key="item.attr_id"
            >
              <!-- 显示对应的单选框 -->
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane
            label="商品图片"
            name="3"
          >
            <!-- 显示上传图片的组件 -->
            <el-upload
              class="upload-demo"
              :action="baseURL"
              :on-preview="handlePreview"
              :on-remove="removePic"
              list-type="picture"
              :headers="headerObj"
              :on-success="uploadSuccess"
            >
              <el-button
                size="small"
                type="primary"
              >点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane
            label="商品内容"
            name="4"
          >
            <!-- 展示富文本编辑器  -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- 确定添加商品的按钮 -->
            <el-button
              type="primary"
              class="add-goods"
              @click="addInfo"
            >添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 显示图片预览的对话框 -->
    <el-dialog
      title="图片预览"
      width="50%"
      :visible.sync="previewPic"
    >
      <el-carousel
        indicator-position="outside"
        ref="carouselRef"
      >
        <el-carousel-item
          v-for="(item, i) in carouselList"
          :key="i"
        >
          <img
            :src="item"
            alt=""
            style="width: 100%;"
          >
        </el-carousel-item>
      </el-carousel>
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'

export default {
  data() {
    return {
      activeIndex: '0',
      // 存数据
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: ''
      },
      // 存规则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择分类选项', trigger: 'blur' }
        ]
      },
      cateList: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      manyDataList: [],
      onlyDataList: [],
      baseURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 显示预览图片需要的数据
      previewPic: false,
      previewPath: '',
      carouselList: []
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      let { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取分类数据失败')
      this.cateList = res.data
    },
    changeCate() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    tabBeforeLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择分类选项')
        return false
      }
    },
    async tabClicked() {
      // 只有当 activeIndex 为 1 的时候，才会处理请求
      if (this.activeIndex === '1') {
        let { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: 'many'
            }
          }
        )
        // 完成数据请求之后的判断和赋值
        if (res.meta.status !== 200) return this.$message.error('动态参数获取失败')
        // 把得到的每一项数据中的 vals 从字符串处理成数组
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
        this.manyDataList = res.data
      } else if (this.activeIndex === '2') {
        let { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: 'only'
            }
          }
        )
        // 完成数据请求之后的判断和赋值
        if (res.meta.status !== 200) return this.$message.error('动态参数获取失败')
        this.onlyDataList = res.data
      }
    },
    handlePreview(file) {
      // 把文件自身的存储信息中的展示路径提供给data中的previewPath
      this.previewPath = file.response.data.url
      this.previewPic = true

      // 通过数组中存储的图片地址，找到对应的索引，改变初始化的索引值
      let index = this.carouselList.findIndex(item => {
        return item === this.previewPath
      })
      this.$nextTick(_ => {
        this.$refs.carouselRef.setActiveItem(index)
      })
    },
    uploadSuccess(res) {
      // 往数组中存储将来用于展示轮播图的地址
      this.carouselList.push(res.data.url)

      let picPath = {
        pic: res.data.tmp_path
      }
      this.addForm.pics.push(picPath)
    },
    removePic(file) {
      // 这里的file组件内部提供的，存储了当前文件的一些信息
      let filePath = file.response.data.tmp_path
      // 1.0 循环pics数组，拿到该路径对应的 索引
      // 使用 findIndex 方法循环，条件是路径名称, 返回值刚好就是索引
      let index = this.addForm.pics.findIndex(item => {
        return item.pic === filePath
      })
      // 2.0 根据所以删除对应的一项数据
      this.addForm.pics.splice(index, 1)
      this.carouselList.splice(index, 1)
    },
    addInfo() {
      // 调用表单的预校验功能
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写表单的必须项')
        let newAddform = _.cloneDeep(this.addForm)
        newAddform.goods_cat = newAddform.goods_cat.join()

        newAddform.attrs = []
        // 动态参数的处理
        this.manyDataList.forEach(item => {
          let obj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join()
          }
          newAddform.attrs.push(obj)
        })
        // 静态属性的处理
        this.onlyDataList.forEach(item => {
          let obj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          newAddform.attrs.push(obj)
        })

        let { data: res } = await this.$http.post('goods', newAddform)
        if (res.meta.status !== 201) return this.$message.error('添加商品失败')
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    // 用来实时返回一个较为准确的三级分类的id
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps {
  margin: 30px 0;
}

.el-form {
  padding-bottom: 40px;
}

.el-form-item {
  margin: 20px 0;
}

.el-input {
  width: 80%;
}

.add-goods {
  margin-top: 40px;
}
</style>